package com.mrd.gtimpframe.action;

import com.github.pagehelper.PageHelper;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.InspectionGoods;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.InspectionGoodsBiz;
import com.mrd.gtimp.order.entity.DeclaContainer;
import com.mrd.gtimpframe.entity.DeclaCheckContent;
import com.mrd.gtimpframe.entity.DeclaCheckTracking;
import com.mrd.gtimpframe.service.VerifyBiz;
import com.mrd.util.LoginUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * Created by dark on 17/7/20.
 */
@Controller
@RequestMapping("/api/verify")
public class VerifyAction {

    @Resource
    private DeclarationBiz declarationBiz;
    @Resource
    private VerifyBiz verifyBiz;

    @Resource
    private InspectionGoodsBiz inspectionGoodsBiz;

    /**
     * 旧数据转换
     */
    @RequestMapping("/transformOldData")
    public void transformOldData() {
        try {
            List<InspectionGoods> inspectionGoodsList = inspectionGoodsBiz.findAllEntity();
            verifyBiz.transformOldData(inspectionGoodsList);
        } catch (QueryException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成查验记录-获取查验对象相关信息
     *
     * @param bussId 业务编号
     */
    @RequestMapping("/getAboutInfo")
    @ResponseBody
    public Map<String, Object> getAboutInfo(
            String bussId) {
        Map<String, Object> result = new HashedMap();
        if (StringUtils.isEmpty(bussId)) {
            result.put("error_code", "1");
            result.put("content", "");
            return result;
        }
        Declaration declaration = null;
        try {
            declaration = declarationBiz.findEntityById(bussId);
        } catch (QueryException e) {
            e.printStackTrace();
            result.put("error_code", "1");
            result.put("content", "后台错误");
            return result;
        }
        if (declaration != null) {
            List<DeclaContainer> containerList = declaration.getDeclaContainers();
            List<Object> rootContaList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(containerList)) {
                for (DeclaContainer declaContainer : containerList) {
                    List<Declaration> declarationList = declarationBiz.findListByContainerNo("%" + declaContainer.getContainerNo() + "%");
                    List<Object> bindDeclaList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(declarationList)) {
                        for (Declaration d : declarationList) {
                            if (!d.getId().equalsIgnoreCase(declaration.getId())) {

                                Map<String, Object> declaMap = new HashedMap();
                                declaMap.put("bussId", d.getId());
                                declaMap.put("bussNo", d.getBusinessId());
                                declaMap.put("ioer", d.getCompany_name());
                                declaMap.put("trueUser", d.getShipper().getCompany());
                                declaMap.put("declaNo", d.getSno());
                                List<String> contaList = new ArrayList<>();
                                for (DeclaContainer container : d.getDeclaContainers()) {
                                    contaList.add(container.getContainerNo());
                                }
                                declaMap.put("contaList", contaList);

                                List<Object> goodsList = new ArrayList<>();
                                for (Commodity commodity : d.getCommodities()) {
                                    Map<String, Object> commodityMap = new HashedMap();
                                    commodityMap.put("goodsName", commodity.getName());
                                    commodityMap.put("goodsId", commodity.getId());
                                    goodsList.add(commodityMap);
                                }
                                declaMap.put("goodsList", goodsList);
                                bindDeclaList.add(declaMap);
                            }
                        }
                    }
                    Map<String, Object> ctMap = new HashedMap();
                    ctMap.put("contaNo", declaContainer.getContainerNo());
                    ctMap.put("bindDeclaList", bindDeclaList);
                    rootContaList.add(ctMap);
                }
            }

            Map<String, Object> contentMap = new HashedMap();
            contentMap.put("bussId", declaration.getId());
            contentMap.put("bussNo", declaration.getBusinessId());
            contentMap.put("ioer", declaration.getCompany_name());
            contentMap.put("trueUser", declaration.getShipper().getCompany());
            contentMap.put("declaNo", declaration.getSno());
            contentMap.put("contaList", rootContaList);
            List<Commodity> commodityList = declaration.getCommodities();
            List<Object> goodsList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(commodityList)) {
                for (Commodity commodity : commodityList) {
                    Map<String, Object> commodityMap = new HashedMap();
                    commodityMap.put("goodsName", commodity.getName());
                    commodityMap.put("goodsId", commodity.getId());
                    goodsList.add(commodityMap);
                }
            }
            contentMap.put("goodsList", goodsList);


            List<Map<String, Object>> contentList = new ArrayList<>();
            contentList.add(contentMap);

            result.put("content", contentList);
        }
        result.put("error_code", "0");

        return result;
    }

    /**
     * 生成查验记录，报关单为已受理状态的报关单才能生成查验记录
     *
     * @param records 查验内容的json字符串
     */
    @Transactional
    @RequestMapping("/initRecord")
    @ResponseBody
    public Map<String, Object> initRecord(String records) {
        Map<String, Object> result = new HashedMap();
        if (StringUtils.isEmpty(records)) {
            result.put("error_code", "1");
            return result;
        }
        JSONObject recordsObject = JSONObject.fromObject(records);
        JSONArray jsonArray = recordsObject.getJSONArray("records");
        if (jsonArray != null) {
            List<String> prop = new ArrayList<>();
            prop.add("state");
            for (Object o : jsonArray) {
                JSONObject jsonObject = JSONObject.fromObject(o);
                CheckRecord checkRecord =
                        (CheckRecord) JSONObject.toBean(jsonObject, CheckRecord.class);
                User user = LoginUtil.getLoginUser();
                if (checkRecord != null && user != null) {
                    String bussId = checkRecord.getBussId();
                    try {
                        Declaration declaration = declarationBiz.findEntityById(bussId);
                        if (declaration != null) {
                            DeclaCheckTracking checkTracking =
                                    verifyBiz.saveCheckRecord(checkRecord, user);
                            if (checkTracking != null) {
                                declaration.setState(Declaration.DeclarationBusinessState.VERIFY_ING);
                                declarationBiz.updateEntity(declaration, prop);
                                List<DeclaCheckContent> declaCheckContentList =
                                        checkTracking.getDeclaCheckContentList();
                                if (CollectionUtils.isNotEmpty(declaCheckContentList)) {
                                    for (DeclaCheckContent checkContent : declaCheckContentList) {
                                        verifyBiz.sendSMS(checkContent, null);
                                    }
                                }
                                result.put("error_code", "0");
                                return result;
                            }
                        }
                    } catch (QueryException e) {
                        e.printStackTrace();
                    } catch (SaveException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        result.put("error_code", "1");
        return result;
    }

    /**
     * 根据查验跟踪id获取报关显示相关信息
     */
    @RequestMapping("/declaInfo")
    @ResponseBody
    public Map<String, Object> decalInfo(
            String trackId) {
        Map<String, Object> rtn = verifyBiz.declaInfo(trackId);
        if (rtn != null) {
            rtn.put("error_code", "0");
        } else {
            rtn = new HashMap<String, Object>();
            rtn.put("error_code", "1");
        }
        return rtn;
    }

    /**
     * 根据查验跟踪id获取查验记录
     */
    @RequestMapping("/showResult")
    @ResponseBody
    public Map<String, Object> showResult(
            String trackId) {
        Map<String, Object> rtn = new HashMap<String, Object>();
        List<Map<String, Object>> conts = verifyBiz.verifyContentByTrack(trackId);
        if (conts != null && conts.size() > 0) {
            rtn.put("error_code", "0");
            rtn.put("content", conts);
        } else {
            rtn.put("error_code", "1");
        }
        return rtn;
    }

    /**
     * 查验结果保存
     */
    @RequestMapping("/saveResult")
    @ResponseBody
    public Map saveResult(
            @RequestBody(required = true) Map<String, Object> map) {

        Map<String, String> result = new HashMap<String, String>();
        result.put("error_code", "1");
        if (!map.containsKey("contentId") || map.get("contentId").toString().length() == 0) {
            result.put("errMsg", "跟踪id不合法");
        } else if (!map.containsKey("status") && map.get("status").toString().length() == 0) {
            result.put("errMsg", "状态值不合法");
        } else if ("2".equals(map.get("status")) && (!map.containsKey("reasonId") || ((List) map.get("reasonId")).size() == 0)) {
            result.put("errMsg", "不通过原因不能为空");
        } else {
            /*boolean rtn = verifyBiz.resultSave(map);
            if (rtn) {
                result.put("error_code", "0");
            } else {
                result.put("errMsg", "保存操作失败");
            }*/
            try {
                verifyBiz.resultSave(map);
                result.put("error_code", "0");
            } catch (RuntimeException re) {
                result.put("errMsg", "保存操作失败");
            }
        }

        return result;
    }


    @RequestMapping("/countNotPassListPage")
    public String countNotPassListPage() {
        return "/gtimpframe/nopassVerify/countMain";
    }

    /**
     * 查验不通过记录统计-查询
     */
    @RequestMapping("/count/notPassVerify/search")
    @ResponseBody
    public Page<Map<String, Object>> countNotPassSearch(Jqgrid jqgrid) {
        Pageable page = jqgrid.getPage();
        int pageNumber = page.getPageNumber();
        int pageSize = page.getPageSize();
        //分页
        PageHelper.startPage(pageNumber + 1, pageSize);
        Map<String, Object> parameterMap = new HashMap<>();

        //组装查询条件
        Filter filter = jqgrid.getFilters();
        if (filter != null) {
            List<SearchRule> searchRuleList = filter.getRules();
            if (CollectionUtils.isNotEmpty(searchRuleList)) {
                for (SearchRule searchRule : searchRuleList) {
                    parameterMap.put(searchRule.getField(), searchRule.getData());
                }
            }
        }

        //排序
        Sort.Order order = jqgrid.getOrder();
        if (order != null) {
            String direction = order.getDirection().toString();
            String propertyName = order.getProperty();
            PageHelper.orderBy(propertyName + " " + direction);
        }
        return verifyBiz.selectNoPass(page, parameterMap);
    }

    /**
     * 查验不通过记录统计-获取不通过类型
     */
    public Map<String, Object> notPassCategoryJsonEnum() {
        return null;
    }

    /**
     * 查验不通过记录统计-获取不通过原因
     */
    public Map<String, Object> notPassDataJsonEnum() {
        return null;
    }

    /**
     * 查验不通过查询参数
     */
    public static class NopassSearchRecord {
        /**
         * 供应商ID
         */
        private String supplier;
        /**
         * 客户公司ID
         */
        private String customerCom;
        /**
         * 查验时间从，格式yyyy-MM-dd
         */
        private String verifyTimeAfter;
        /**
         * 查验时间至，格式yyyy-MM-dd
         */
        private String verifyTimeBefore;
        /**
         * 不通过类型ID
         */
        private String notPassCategory;
        /**
         * 不通过原因ID，数组类型
         */
        private List<String> notPassReason;

        public String getSupplier() {
            return supplier;
        }

        public void setSupplier(String supplier) {
            this.supplier = supplier;
        }

        public String getCustomerCom() {
            return customerCom;
        }

        public void setCustomerCom(String customerCom) {
            this.customerCom = customerCom;
        }

        public String getVerifyTimeAfter() {
            return verifyTimeAfter;
        }

        public void setVerifyTimeAfter(String verifyTimeAfter) {
            this.verifyTimeAfter = verifyTimeAfter;
        }

        public String getVerifyTimeBefore() {
            return verifyTimeBefore;
        }

        public void setVerifyTimeBefore(String verifyTimeBefore) {
            this.verifyTimeBefore = verifyTimeBefore;
        }

        public String getNotPassCategory() {
            return notPassCategory;
        }

        public void setNotPassCategory(String notPassCategory) {
            this.notPassCategory = notPassCategory;
        }

        public List<String> getNotPassReason() {
            return notPassReason;
        }

        public void setNotPassReason(List<String> notPassReason) {
            this.notPassReason = notPassReason;
        }
    }

    public static class CheckRecord {

        /**
         * 报关单ID
         */
        private String bussId;
        /**
         * 创建时间
         */
        private String ctime;
        /**
         * 查验项目列表
         */
        private List<String> itemList;
        /**
         * 查验单位列表
         */
        private List<String> deptList;
        /**
         * 柜号列表
         */
        private List<String> ContaList;
        /**
         * 商品列表
         */
        private List<String> goodsList;

        /**
         * 其他查验单位
         */
        private String otherDepts;

        /**
         * 其他查验项目
         */
        private String otherItems;

        public String getBussId() {
            return bussId;
        }

        public void setBussId(String bussId) {
            this.bussId = bussId;
        }

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public List<String> getItemList() {
            return itemList;
        }

        public void setItemList(List<String> itemList) {
            this.itemList = itemList;
        }

        public List<String> getDeptList() {
            return deptList;
        }

        public void setDeptList(List<String> deptList) {
            this.deptList = deptList;
        }

        public List<String> getContaList() {
            return ContaList;
        }

        public void setContaList(List<String> contaList) {
            ContaList = contaList;
        }

        public List<String> getGoodsList() {
            return goodsList;
        }

        public void setGoodsList(List<String> goodsList) {
            this.goodsList = goodsList;
        }

        public String getOtherDepts() {
            return otherDepts;
        }

        public void setOtherDepts(String otherDepts) {
            this.otherDepts = otherDepts;
        }

        public String getOtherItems() {
            return otherItems;
        }

        public void setOtherItems(String otherItems) {
            this.otherItems = otherItems;
        }
    }

}
